<template>
  <div class="radar-data-viewer">
    <div class="content-wrapper">
      <!-- 左侧菜单 -->
      <div class="sidebar">
        <div
          v-for="item in menuItems"
          :key="item.id"
          :class="['menu-item', { active: activeMenu === item.id }]"
          @click="selectMenu(item.id)"
        >
          <i :class="item.icon"></i>
          <span>{{ item.name }}</span>
        </div>
      </div>

      <!-- 右侧内容区 -->
      <div class="content">
        <!-- 动态查询表单 -->
        <div class="query-form">
          <el-form :model="queryParams" label-width="120px" inline>
            <!-- 动态生成表单项 -->
            <el-form-item
              v-for="(field, index) in formFields"
              :key="index"
              :label="field.label"
            >
              <!-- 文本输入框 -->
              <el-input
                v-if="field.type === 'input'"
                v-model="queryParams[field.prop]"
                :placeholder="field.placeholder || '请输入'"
                clearable
              />

              <!-- 单个日期时间选择器 -->
              <el-date-picker
                v-else-if="field.type === 'datetime'"
                v-model="queryParams[field.prop]"
                type="datetime"
                placeholder="选择日期时间"
                value-format="yyyy-MM-dd HH:mm:ss"
              />

              <!-- 时间段选择器（雷达站址专用） -->
              <el-date-picker
                v-else-if="field.type === 'daterange'"
                v-model="queryParams[field.prop]"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="yyyy-MM-dd HH:mm:ss"
                style="width: 400px"
              />

              <!-- 下拉选择 -->
              <el-select
                v-else-if="field.type === 'select'"
                v-model="queryParams[field.prop]"
                :placeholder="field.placeholder || '请选择'"
                clearable
              >
                <el-option
                  v-for="opt in field.options"
                  :key="opt.value"
                  :label="opt.label"
                  :value="opt.value"
                />
              </el-select>

              <!-- 范围选择 -->
              <div v-else-if="field.type === 'range'" class="range-inputs">
                <el-input
                  v-model="queryParams[field.prop + 'Min']"
                  placeholder="最小值"
                  clearable
                />
                <span class="range-separator">至</span>
                <el-input
                  v-model="queryParams[field.prop + 'Max']"
                  placeholder="最大值"
                  clearable
                />
              </div>
            </el-form-item>

            <!-- 操作按钮 -->
            <el-form-item class="form-actions">
              <el-button type="primary" @click="handleQuery">
                <i class="el-icon-search"></i> 查询
              </el-button>
              <el-button @click="resetQuery">
                <i class="el-icon-refresh"></i> 重置
              </el-button>
            </el-form-item>
          </el-form>
        </div>

        <!-- 表格容器 -->
        <div class="table-container">
          <EnhancedTable
            :data="tableData"
            :columns="columnsConfig"
            :total="total"
            :current-page="currentPage"
            :page-size="pageSize"
            :index-bg="selectedIndexBg"
            :odd-row-bg="selectedOddBg"
            :even-row-bg="selectedEvenBg"
            @page-change="handlePageChange"
            @page-size-change="handlePageSizeChange"
            @row-click="handleRowClick"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import EnhancedTable from "@/components/EnhancedTable/index.vue";
import {
  getLocationList,
  getTrackList,
  getRealList,
  getInterfereList,
  getPointList,
  getHrrpList,
  getRdList,
  getJemList,
} from "@/api/datarecord/index.js";

// 定义不同数据类型的表单字段配置
const FORM_FIELDS_CONFIG = {
  radarSites: [
    {
      prop: "timeRange",
      label: "时间范围",
      type: "daterange", // 修改为时间段选择器
    },
  ],
  planeTrack: [
    { prop: "batchNo", label: "批号", type: "input" },
    {
      prop: "targetType",
      label: "目标类型",
      type: "select",
    },
  ],
  trueValueData: [
    { prop: "batchNo", label: "批号", type: "input" },
    {
      prop: "realType",
      label: "真值类型",
      type: "select",
    },
  ],
  interferingData: [
    { prop: "batchNo", label: "批号", type: "input" },
    {
      prop: "interfereType",
      label: "类型",
      type: "select",
      options: [
        { value: "压制", label: "压制干扰" },
        { value: "欺骗", label: "欺骗干扰" },
      ],
    },
  ],
  spotTraceData: [{ prop: "pointId", label: "点号", type: "input" }],
  D1Data: [{ prop: "pointNum", label: "点数", type: "input" }],
  RD: [{ prop: "frameId", label: "帧号", type: "input" }],
  JEM: [{ prop: "engineType", label: "点数", type: "input" }],
};

// 定义不同数据类型的列配置
const COLUMNS_CONFIG = {
  radarSites: [
    { prop: "longitude", label: "经度" },
    { prop: "latitude", label: "纬度" },
    { prop: "sendTime", label: "时间" },
    // { prop: "remark", label: "备注" },
  ],
  planeTrack: [
    { prop: "batchNo", label: "批号" },
    { prop: "longitude", label: "经度" },
    { prop: "latitude", label: "纬度" },
    { prop: "speed", label: "速度" },
    { prop: "sourceId", label: "来源" },
    { prop: "targetType", label: "目标类型" },
    { prop: "trackingStatus", label: "跟踪状态" },
    { prop: "snr", label: "信噪比" },
    { prop: "rcs", label: "RCS" },
    { prop: "direction", label: "跟踪状态" },
    // { prop: "remark", label: "备注" },
  ],
  trueValueData: [
    { prop: "batchNo", label: "批号" },
    // { prop: "uniqueBatchNo", label: "唯一批号" },
    { prop: "longitude", label: "经度" },
    { prop: "latitude", label: "纬度" },
    { prop: "realType", label: "真值类型" },
    // { prop: "remark", label: "备注" },
  ],
  interferingData: [
    { prop: "batchNo", label: "批号" },
    { prop: "interfereDirection", label: "方向" },
    { prop: "interfereType", label: "类型" },
    { prop: "interfereStrength", label: "强度" },
    // { prop: "remark", label: "备注" },
  ],
  spotTraceData: [
    { prop: "pointId", label: "点号" },
    { prop: "frameId", label: "帧号" },
    { prop: "snr", label: "信噪比" },
    { prop: "frameId", label: "帧号" },
    { prop: "sendTime", label: "检测时间" },
    // { prop: "remark", label: "备注" },
  ],
  D1Data: [
    { prop: "pointNum", label: "点数" },
    { prop: "distance", label: "距离" },
    { prop: "sendTime", label: "时间" },
    // { prop: "remark", label: "备注" },
  ],
  RD: [
    { prop: "frameId", label: "帧号" },
    { prop: "pointId", label: "点号" },
    { prop: "sendTime", label: "时间" },
    // { prop: "rdUrl", label: "rd图url" },
  ],
  JEM: [
    { prop: "pointNum", label: "点数" },
    { prop: "spectrumUrl", label: "频谱" },
    { prop: "sendTime", label: "时间" },
    // { prop: "remark", label: "备注" },
  ],
};

export default {
  name: "RadarDataViewer",
  components: {
    EnhancedTable,
  },
  data() {
    return {
      methodsMap: new Map([
        ["radarSites", getLocationList],
        ["planeTrack", getTrackList],
        ["trueValueData", getRealList],
        ["interferingData", getInterfereList],
        ["spotTraceData", getPointList],
        ["D1Data", getHrrpList],
        ["RD", getRdList],
        ["JEM", getJemList],
      ]),
      currentPage: 1,
      pageSize: 10,
      total: 0,
      currentTime: "",
      selectedIndexBg: require("@/assets/images/序号.png"),
      selectedOddBg: require("@/assets/images/单数.png"),
      selectedEvenBg: require("@/assets/images/双数.png"),
      activeMenu: "radarSites",
      queryParams: {
        timeRange: [], // 初始化时间段选择器的值
      },
      menuItems: [
        { id: "radarSites", name: "雷达站址" },
        { id: "planeTrack", name: "航迹数据" },
        { id: "trueValueData", name: "真值数据" },
        { id: "interferingData", name: "干扰数据" },
        { id: "spotTraceData", name: "点迹数据" },
        { id: "D1Data", name: "一维像数据" },
        { id: "RD", name: "RD数据" },
        { id: "JEM", name: "JEM数据" },
      ],
      tableData: [], // 当前表格数据
    };
  },
  computed: {
    activeMenuName() {
      return (
        this.menuItems.find((item) => item.id === this.activeMenu)?.name || ""
      );
    },
    formFields() {
      return FORM_FIELDS_CONFIG[this.activeMenu] || [];
    },
    columnsConfig() {
      return COLUMNS_CONFIG[this.activeMenu] || [];
    },
  },
  mounted() {
    this.getDataList();
    this.updateTime();
    setInterval(this.updateTime, 1000);
    // 初始化查询参数
    this.resetQuery();
  },
  methods: {
    // 获取数据列表
    getDataList() {
      const apiMethod = this.methodsMap.get(this.activeMenu);
      if (!apiMethod) return;

      // 准备请求参数
      const params = {
        pageNum: this.currentPage,
        pageSize: this.pageSize,
        ...this.transformQueryParams(),
      };
      console.log("+++++", params);

      this.loading = true;
      apiMethod(params)
        .then((res) => {
          if (res.code === 200) {
            this.tableData = res.rows;
            this.total = res.total;
          } else {
            this.$message.error(res.msg || "获取数据失败");
          }
        })
        .catch((error) => {
          console.error("API Error:", error);
          this.$message.error("请求数据失败");
        })
        .finally(() => {
          this.loading = false;
        });
    },

    // 转换查询参数为API需要的格式
    transformQueryParams() {
      const transformed = { ...this.queryParams };

      // 处理时间段参数（雷达站址专用）
      if (this.activeMenu === "radarSites" && transformed.timeRange) {
        transformed.startTime = transformed.timeRange[0] || "";
        transformed.endTime = transformed.timeRange[1] || "";
        delete transformed.timeRange;
      }

      // 处理范围查询参数
      Object.keys(transformed).forEach((key) => {
        if (key.endsWith("Min") || key.endsWith("Max")) {
          const prop = key.replace(/(Min|Max)$/, "");
          if (!transformed[prop]) transformed[prop] = {};

          if (key.endsWith("Min")) {
            transformed[prop].min = transformed[key];
          } else {
            transformed[prop].max = transformed[key];
          }
          delete transformed[key];
        }
      });

      // 过滤空值
      Object.keys(transformed).forEach((key) => {
        if (transformed[key] === "" || transformed[key] == null) {
          delete transformed[key];
        }
      });

      return transformed;
    },

    // 页码变化
    handlePageChange(page) {
      this.currentPage = page;
      this.getDataList();
    },

    // 每页数量变化
    handlePageSizeChange(size) {
      this.pageSize = size;
      this.currentPage = 1;
      this.getDataList();
    },

    // 行点击事件
    handleRowClick(row) {
      this.$message.success(`已选择: ${row.name || row.trackId || row.id}`);
    },

    // 选择菜单
    selectMenu(menuId) {
      this.activeMenu = menuId;
      this.currentPage = 1;
      this.resetQuery();
      this.getDataList();
    },

    // 更新时间显示
    updateTime() {
      const now = new Date();
      this.currentTime = now.toLocaleString("zh-CN", {
        year: "numeric",
        month: "2-digit",
        day: "2-digit",
        hour: "2-digit",
        minute: "2-digit",
        second: "2-digit",
      });
    },

    // 查询操作
    handleQuery(value) {
      console.log(value, "+++++");

      this.currentPage = 1;
      this.getDataList();
    },

    // 重置查询条件
    resetQuery() {
      const params = {};
      this.formFields.forEach((field) => {
        if (field.type === "range") {
          params[field.prop + "Min"] = "";
          params[field.prop + "Max"] = "";
        } else if (field.type === "daterange") {
          params[field.prop] = ["", ""]; // 重置时间段选择器
        } else {
          params[field.prop] = "";
        }
      });
      this.queryParams = params;
    },
  },
};
</script>

<style scoped>
.radar-data-viewer {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background: linear-gradient(135deg, #0c162d 0%, #1a2a5e 100%);
  color: #e0f7ff;
  overflow: hidden;
}
::v-deep .el-form-item__label {
  color: #ffffff !important;
}

::v-deep .el-input__inner,
::v-deep .el-range-input,
::v-deep .el-range-separator {
  color: #ffffff !important;
}
.content-wrapper {
  display: flex;
  flex: 1;
  overflow: hidden;
}

.sidebar {
  width: 250px;
  background: rgba(10, 25, 55, 0.7);
  border-right: 1px solid rgba(13, 138, 188, 0.3);
  padding: 20px 0;
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.menu-item {
  padding: 10px 25px;
  display: flex;
  align-items: center;
  gap: 15px;
  cursor: pointer;
  transition: all 0.3s ease;
  font-size: 1.1rem;
  border-left: 4px solid transparent;
}

.menu-item:hover {
  background: rgba(3, 182, 255, 0.3);
}

.menu-item.active {
  background: rgba(3, 182, 255, 0.5);
  border-left: 4px solid #00f2fe;
  color: #fff;
}

.content {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 20px;
  overflow: hidden;
  background: rgba(8, 20, 47, 0.3);
  border: 1px solid rgba(0, 93, 165, 0.5);
  border-radius: 8px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.5);
}

.query-form {
  background: rgba(15, 51, 80, 0.5);
  padding: 20px;
  border-radius: 8px;
  width: 100%;
  margin-bottom: 20px;
  border: 1px solid rgba(0, 93, 165, 0.3);
}

.range-inputs {
  display: flex;
  align-items: center;
}

.range-separator {
  margin: 0 10px;
  color: #7fdbff;
}

.form-actions {
  margin-left: auto;
}

.table-container {
  flex: 1;
  overflow: auto;
  border-radius: 8px;
  background: rgba(15, 51, 80, 0.3);
  border: 1px solid rgba(13, 138, 188, 0.3);
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);
}
</style>